<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="80%" :title="`${drawerProps.title}系统单页`">
    <el-form
      ref="roleFormRef"
      label-width="150px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="item"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="单页名称" prop="name">
        <el-input v-model="item.name" placeholder="请填写单页名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="单页标识" prop="code">
        <el-input v-model="item.code" placeholder="请填写单页标识" clearable></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <WangEditor v-model:value="item.content" height="400px" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="HelpCenterEdit">
import { ref, reactive, onUpdated } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Cms } from "@/api/interface";
import { getHelpCenterInfo } from "@/api/modules/cms";
import WangEditor from "@/components/WangEditor/index.vue";

let item = ref<Cms.HelpCenter>({
  id: 0,
  name: "",
  code: "",
  content: "",
  createdAt: "",
  updatedAt: ""
});
onUpdated(() => {
  if (drawerProps.value.title == "编辑") {
    const adminRole = getHelpCenterInfo({ id: drawerProps.value.row.id });
    adminRole.then(res => {
      item.value = res.data;
    });
  } else {
    item.value = { id: 0, name: "", code: "", content: "", createdAt: "", updatedAt: "" };
  }
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Cms.HelpCenter>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};
const rules = reactive({
  name: [{ required: true, message: "请填写单页名称" }],
  code: [{ required: true, message: "请填写单页标识" }],
  content: [{ required: true, message: "请填写内容" }]
});
// 提交数据（新增/编辑）
const roleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  roleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(item.value);
      ElMessage.success({ message: `${drawerProps.value.title}系统单页成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
